﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Linq;
using Scoreboard.Model.Authentication;
using Scoreboard.Data;
using System.ComponentModel;

namespace Scoreboard.Model
{
	public partial class Tournament
	{
		public Participant Me
		{
			get
			{
				return Participants
					.Where(p => p.BelongsTo(WebContext.Current.User))
					.SingleOrDefault();
			}
		}

		public bool IsStarted
		{
			get
			{
				return Stages != null && Stages.Count > 0;
			}
		}

		public bool Participates(ScoreboardUser user)
		{
			return Participants
				.Where(p => p.BelongsTo(user))
				.Count() != 0;
		}

		public bool UserCanAddResult(ScoreboardUser user)
		{
			if (!Participates(user))
			{
				return false;
			}
			var group = GetCurrentGroupForCurrentUser();
			if (group == null || group.Stage.IsFinished)
			{
				return false;
			}

			return group.GetUsersLeftToPlayWith().Count() > 0;
		}

		public void RefreshAllGroups()
		{
			foreach (var stage in Stages)
			{
				if (stage.Groups != null)
				{
					foreach (var group in stage.Groups)
					{
						group.Refresh();
					}
				}

				if (stage.SubTournaments != null)
				{
					foreach (var subtournament in stage.SubTournaments)
					{
						subtournament.RefreshAllGroups();
					}
				}
			}
		}

		public Group GetCurrentGroupForCurrentUser()
		{
			var lastTournamentStage = Stages.OrderBy(s => s.IndexNumber).Last();
			return GetCurrentGroupForCurrentUserFromStage(lastTournamentStage);
		}

		private Group GetCurrentGroupForCurrentUserFromStage(Stage stage)
		{
			if (stage.ContainsGroups)
			{
				return stage.Groups
					.Where(g => g.ContainsUser(WebContext.Current.User))
					.SingleOrDefault();
			}

			foreach (var subtournament in stage.SubTournaments)
			{
				var group = GetCurrentGroupForCurrentUserFromSubtournament(subtournament);
				if (group != null)
				{
					return group;
				}
			}
			return null;
		}

		private Group GetCurrentGroupForCurrentUserFromSubtournament(SubTournament subtournament)
		{
			if (subtournament.Stages.Count == 0)
			{
				return null;
			}
			return GetCurrentGroupForCurrentUserFromStage(subtournament.Stages.OrderBy(s => s.IndexNumber).Last());
		}

		private static bool IsGroupFinished(Group group)
		{
			return group.Games.Count == GetGamesCount(group.RoundsNumber, group.Participants.Count);
		}

		private static int GetGamesCount(int roundsCount, int playersCount)
		{
			int gamesCountPerRound = 0;
			for (int i = 1; i < playersCount; i++)
			{
				gamesCountPerRound += i;
			}

			return gamesCountPerRound * roundsCount;
		}
	}
}
